package com.ruicar.afs.cloud.bizcommon.print.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.bizcommon.dto.print.TemplateDto;
import com.ruicar.afs.cloud.bizcommon.dto.rules.tree.RuleTreeDto;
import com.ruicar.afs.cloud.bizcommon.enums.rules.RuleStatus;
import com.ruicar.afs.cloud.bizcommon.print.common.TemplatePringConstants;
import com.ruicar.afs.cloud.bizcommon.print.condition.ComPrintFormManageCondition;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.bizcommon.rules.entity.AfsRuleInfo;
import com.ruicar.afs.cloud.bizcommon.rules.service.AfsRuleInfoService;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author phong
 * @version 1.0
 * @description: 打印模板管理模块
 * @created 2020/5/19 11:38
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(value = "template", description = "打印模板管理模块")
@RequestMapping("/template")
public class TemplateController {

    private final ComPrintFormManageService comPrintFormManageService;
    private final AfsRuleInfoService afsRuleInfoService;


    @Transactional
    @PostMapping("/add")
    @ApiOperation(value = "保存模板信息")
    public IResponse<Boolean> saveTemplate(@RequestBody @Validated ComPrintFormManage comPrintFormManage) throws ParseException {
        return IResponse.success(comPrintFormManageService.saveTemplate(comPrintFormManage));
    }

    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "删除模板")
    public IResponse<Boolean> delTemplate(@PathVariable String id) {
        return IResponse.success(comPrintFormManageService.delTemplate(id));
    }

    @PostMapping("/edit")
    @ApiOperation(value = "编辑模板")
    public IResponse<Boolean> modifyTemplate(@RequestBody @Validated ComPrintFormManage comPrintFormManage) {
        return IResponse.success(comPrintFormManageService.modifyTemplate(comPrintFormManage));
    }

    @RequestMapping(value = "/disable/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "禁用模板")
    @Transactional
    @SysLog("禁用模板")
    public IResponse<Boolean> disable(@ApiParam("模板唯一id标识") @PathVariable String id) {
        ComPrintFormManage template = comPrintFormManageService.getById(id);
        if (template == null) {
            return IResponse.fail("通过id获取模板失败");
        }
        template.setIsEnable(TemplatePringConstants.NO);
        comPrintFormManageService.updateById(template);
        // 停用规则
        List<AfsRuleInfo> afsRuleInfos = afsRuleInfoService.list(Wrappers.<AfsRuleInfo>lambdaQuery()
                .eq(AfsRuleInfo::getRuleNo, id)
                .eq(AfsRuleInfo::getStatus, RuleStatus.ACTIVE));
        afsRuleInfos.forEach(info -> {
            //先反激活再失效
            afsRuleInfoService.deActiveRuleWithoutPublish(info.getId());
        });

        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/enable/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "启用模板")
    @Transactional
    @SysLog("启用模板")
    public IResponse<Object> enable(@ApiParam("模板唯一id标识") @PathVariable String id) {
        ComPrintFormManage template = comPrintFormManageService.getById(id);
        if (template == null) {
            return IResponse.fail("通过id获取模板失败");
        }
        template.setIsEnable(TemplatePringConstants.YES);
        comPrintFormManageService.updateById(template);
        // 启用规则
        List<AfsRuleInfo> afsRuleInfos = afsRuleInfoService.list(Wrappers.<AfsRuleInfo>lambdaQuery()
                .eq(AfsRuleInfo::getRuleNo, id)
                .orderByDesc(AfsRuleInfo::getRuleVersion));
        if (CollUtil.isNotEmpty(afsRuleInfos)) {
            AfsRuleInfo info = afsRuleInfos.stream().findFirst().get();
            afsRuleInfoService.activeRule(info.getId());
        }
        return new IResponse().setData(true);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询模板")
    public IResponse queryTemplateList(@RequestBody QueryCondition<TemplateDto> queryCondition) {
        return comPrintFormManageService.query(queryCondition);
    }

    @GetMapping(value = "/preview/{printFormId}")
    @ApiOperation(value = "打印模板预览")
    public void preview(HttpServletResponse response, @PathVariable String printFormId) {
        BufferedInputStream bufferedInputStream = null;
        try {
            String path = comPrintFormManageService.preview(printFormId);
            bufferedInputStream = FileUtil.getInputStream(path);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=" + HttpUtil.encodeUtf8("预览.pdf"));
            IoUtil.copy(bufferedInputStream, response.getOutputStream(), 1024);
            response.getOutputStream().flush();
            // 删除临时文件
            FileUtil.del(path);
        } catch (IOException e) {
            log.error("读取文件失败", e);
        } finally {
            IoUtil.close(bufferedInputStream);
        }
    }

    /**
     * 模板规则树
     *
     * @param ruleGroup
     * @param ruleNo
     * @return
     */
    @PostMapping("/loadTemplateRuleTree/{ruleGroup}/{ruleNo}")
    public IResponse<List<RuleTreeDto>> loadTemplateRuleTree(@PathVariable("ruleGroup") String ruleGroup, @PathVariable("ruleNo") String ruleNo) {
        // 通过规则编号查询是否有对应的规则
        AfsRuleInfo info = afsRuleInfoService.getOne(Wrappers.<AfsRuleInfo>lambdaQuery()
                .eq(AfsRuleInfo::getRuleGroup, ruleGroup)
                .eq(AfsRuleInfo::getRuleNo, ruleNo)
                .orderByDesc(AfsRuleInfo::getRuleVersion), false);
        if (info == null) {
            return IResponse.success(CollUtil.newArrayList());
        }
        return IResponse.success(afsRuleInfoService.loadRuleTree(info.getId())).setMsg(String.valueOf(info.getId()));
    }

    /**
     * 模板规则树
     *
     * @param ruleId
     * @return
     */
    @PostMapping("/loadTemplateRuleTreeById")
    public IResponse<List<RuleTreeDto>> loadTemplateRuleTreeById(@RequestParam("ruleId") String ruleId) {
        if(!ObjectUtils.isEmpty(ruleId)){
            return IResponse.success(afsRuleInfoService.loadRuleTree(Long.valueOf(ruleId))).setMsg(ruleId);
        }else{
            return IResponse.success(new ArrayList<>());
        }

    }

    /**
     * 失效规则
     *
     * @param ruleId
     * @return
     */
    @PostMapping("/deActiveTemplateRuleById/{ruleId}")
    public IResponse deActiveTemplateRuleById(@PathVariable("ruleId") String ruleId) {
        //先反激活再失效
        afsRuleInfoService.deActiveRuleWithoutPublish(Long.valueOf(ruleId));
        return IResponse.success("失效成功");
    }
}
